package com.niit.cms.controller;

import com.github.pagehelper.PageInfo;
import com.niit.cms.entity.News;
import com.niit.cms.service.NewsService;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description:
 * @Author: cao_jiaqi
 * @CreateTime： 2022/6/30 0:45
 */
@Controller
public class NewsController {
    @Resource
    private NewsService newsService;

    @GetMapping("/news")
    public String news(Model model,
                       @RequestParam(name = "pageNum", required = false, defaultValue = "1") String pageNum,
                        @RequestParam(name = "type", required = false, defaultValue = "职场法则") String type){
        //页码
        Integer page = Integer.parseInt(pageNum);
        //分类
        model.addAttribute("type", type);
        //查询新闻分类
        List<String> typeList = newsService.queryNewsType();
        model.addAttribute("typeList", typeList);
        //分页查询新闻
        List<News> newsList = newsService.queryListByType(type,page);
        PageInfo<News> pageInfo = new PageInfo<>(newsList);
        model.addAttribute("pageInfo", pageInfo);
        //热点新闻
        List<News> newsList2 = newsService.queryOrderedListByLmit("read_num",10);
        model.addAttribute("newsList2", newsList2);
        //最新资讯
        List<News> newsList3 = newsService.queryOrderedListByLmit("pubdate",10);
        model.addAttribute("newsList3", newsList3);
        return "news";

    }
    /**
     * @Description: 新闻详情页
     * @Author: cao_jiaqi
     * @CreateTime: 2022/6/30 13:12
     * @return: java.lang.String
     **/
    @GetMapping("/newsDetail/{id}")
    public String newsDetail(Model model, @PathVariable("id") Integer id){
        //新闻详情
        News news = newsService.queryById(id);
        news.setReadNum(news.getReadNum() + 1);//阅读量加1
        newsService.update(news);
        model.addAttribute("news", news);
        //相关阅读
        List<News> newsList = newsService.queryOrderedListByTypeLimit(news.getType(), "read_num", 12);
        model.addAttribute("newsList", newsList);
        //热点新闻
        List<News> newsList2 = newsService.queryOrderedListByLmit("read_num",10);
        model.addAttribute("newsList2", newsList2);
        //最新资讯
        List<News> newsList3 = newsService.queryOrderedListByLmit("pubdate",10);
        model.addAttribute("newsList3", newsList3);
        return "news_detail";
    }
}
